
import pymysql


class DBUtil(object):
    def __init__(self, ip, dbUser, dbPass, dbName):
        self.db = None
        self.cursor = None
        self.ip = ip
        self.dbUser = dbUser
        self.dbPass = dbPass
        self.dbName = dbName

    # 创建连接
    def conn(self):
        self.db = pymysql.connect(self.ip, self.dbUser, self.dbPass, self.dbName)
        self.cursor = self.db.cursor()

    # 关闭连接
    def close(self):
        self.cursor.close()
        self.db.close()

    # 单个查询
    def query_one(self, sql):
        if not self.db:
            self.conn()

        try:
            self.cursor.execute(sql)
            return self.cursor.fetchone()
        except Exception as ex:
            print("查询失败:", ex)
        finally:
            self.close()

    # 批量查询
    def query_all(self, sql):
        if not self.db:
            self.conn()

        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as ex:
            print("查询失败:", ex)
        finally:
            self.close()

    # 增
    def insert(self, sql):
        return self._common(self, sql)

    # 改
    def update(self, sql):
        return self._common(self, sql)

    # 删
    def delete(self, sql):
        return self._common(self, sql)

    # 公共
    def _common(self, sql):
        if not self.db:
            self.conn()

        try:
            count = self.cursor.execute(sql)
            self.db.commit()
            return count
        except Exception as ex:
            print("事务执行失败:", ex)
            self.db.rollback()
            raise Exception("事务执行失败:", ex)
        finally:
            self.close()


if __name__ == "__main__":
    dbutil = DBUtil("localhost", "root", "123456", "ssm")

    rows = dbutil.query_all("select * from  tb_mv")

    # print("rows= ", rows)

    index = 1
    for row in rows:
        print(index, "-", row[1], "-", row[2])
        index += 1



